var t = getApp(), e = t.requirejs("core"), foxui = t.requirejs("foxui"), wxParse = t.requirejs("wxParse/wxParse");
var selectIndex; // 选择的大规格key
var attrIndex; // 选择的小规格的key
var selectIndexArray = []; // 选择属性名字的数组
var selectAttrid = []; // 选择的属性id
Page({
    data: {
      icons: t.requirejs("icons"),
      indicatorDots: !0,
      autoplay: !0,
      interval: 5e3,
      duration: 500,
      circular: !0,
      beforeColor: "rbga(0,0,0,.5)",
      afterColor: "white",
      page: 1,
      loading: false,
      loaded: false,
      type: "",
      merchid: 0,
      merch: {},
      merchcoupon: [],
      couponList: [],
      bannerImg: [],
      result: {
        bannerheight: "",
        specheight: "",
      },
      keywords: "",
      oneclass: [],
      onestatus: 0,
      twoclass: [],
      twostatus: 0,
      cate: 0,
      list: [],
      cart_num: 1,
      cover: false,
      coupon: false,
      shop: false,
      spec: false,
      specTopNum: 0,
      specFloorstatus: false,
      specbanner: [],
      speclength: 0,
      optionid: "",
    },
    onLoad: function(p) {
      this.setData({
        type: p.type,
        merchid: p.merchid,
      })
    },
    onShow: function() { 
      var that = this;
      that.setData({
        imgUrl: t.globalData.approot
      });
      wx.getSystemInfo({
        success: function(t) {
          var e = t.windowWidth / 2.5;
          that.setData({
            swiperheight: e
          });
        }
      });
      t.getCache("isIpx") ? that.setData({
        isIpx: !0,
        iphonexnavbar: "fui-iphonex-navbar",
        paddingb: "padding-b"
      }) : that.setData({
        isIpx: !1,
        iphonexnavbar: "",
        paddingb: ""
      })
      wx.getLocation({
        type: "wgs84",
        success: function(res) {
          that.setData({
            latitude: res.latitude,
            longitude: res.longitude,
          }), that.getInfo()
        },
        fail: function(t) {
          // e.alert("取消位置信息将无法定位商家距离！"), 
          that.setData({
            latitude: "",
            longitude: "",
          }), that.getInfo()
        }
      }), that.merchcoupon(), that.getCart();
      t.checkAuth();
    },
    getInfo: function() {
      var t = this, td = t.data, type = td.type, merchid = td.merchid, lat = td.latitude, lng = td.longitude;
      e.get("merch/index", { type: type, merchid: merchid, lat: lat, lng: lng, }, function(r) {
        if(r.error==0){
          t.setData({
            merch: r.merch,
            distance: r.distance,
            bannerImg: r.advs,
            oneclass: r.yiji_category,
            twoclass: r.erji_category,
            // onestatus: r.yiji_category[0].id,
            // twostatus: r.erji_category[0].id,
            merch_cart: r.merch_cart,
          }), t.getList(), t.getCart();
        }else{
          wx.showModal({
            title: "提示",
            content: r.message,
            showCancel: false,
            confirmText: "确定",
            success: (data) => {
              if (data.confirm) {
                wx.navigateBack({ changed: true });
              }
            }
          })
        }
      });
    },
    merchcoupon: function() {
      var th = this, shid = th.data.merchid;
      e.get("merch/get_coupon_list", {
        shanghuid: shid,
      }, function(r) {
        r.error==0?th.setData({ merchcoupon: r.list }):"";
      });
    },
    getList: function() {
      var t = this;
      t.setData({
          loading: true
      }), e.get("merch/index/get_goods", {
          page: t.data.page,
          type: t.data.type,
          merchid: t.data.merchid,
          keywords: t.data.keywords,
          cate: t.data.cate,
      }, function(e) {
          var i = {
            loading: false,
            total: e.total,
            pagesize: e.pagesize,
            show: !0
          };
          e.list.length > 0 && (i.page = t.data.page + 1, i.list = t.data.list.concat(e.list), 
          e.list.length < e.pagesize && (i.loaded = true)), t.setData(i);
      });
    },
    getFenlei: function() {
      let t = this;
      e.get("merch/index/get_ejcategory", { cate: t.data.cate, }, function(r) {
        t.setData({
          type: t.data.type,
          twoclass: r.category,
        }), t.getList();
      });
    },
    bindSearch: function(p) {
      this.setData({
        list: [],
        page: 1,
        keywords: p.detail.value,
        loaded: false,
        cate: 0,
      }), this.getList();
    },
    url: function(p) {
      var url = "", userinfoOpenid = t.getCache("userinfo_openid");
      if(userinfoOpenid) url = p.currentTarget.dataset.url;
      else url = "/pages/auth/index"
      wx.navigateTo({ url: url, })
    },
    call: function(p) {
      let phone = p.currentTarget.dataset.tel;
      wx.makePhoneCall({
        phoneNumber: phone,
        success:function() { console.log("成功！"); },
        fail:function() { console.log("失败！"); }
      })
    },
    loca: function (p) {
      let dataset = p.currentTarget.dataset,
          lat = parseFloat(dataset.lat), lng = parseFloat(dataset.lng), 
          nme = dataset.name, add = dataset.address;
      wx.openLocation({
        latitude: lat,
        longitude: lng,
        name: nme,
        address: add
      })
    },
    oneclass: function(t) {
      var a = Number(e.data(t).type), onestatus = Number(this.data.onestatus);
      if(a==onestatus) return false;
      this.setData({
        onestatus: a,
        twostatus: 0,
        cate: a,
        list: [],
        page: 1,
        loaded: false,
      }), this.getFenlei();
    },
    twoclass: function(t) {
      var a = Number(e.data(t).type), twostatus = Number(this.data.twostatus);
      if(a==twostatus) return false;
      this.setData({
          list: [],
          page: 1,
          twostatus: a,
          cate: a,
          loaded: false,
      }), this.getList();
    },
    imagesHeight: function(t) {
      var a = t.detail.width, e = t.detail.height, i = t.target.dataset.type, s = this;
      wx.getSystemInfo({
          success: function(t) {
            s.data.result[i] = t.windowWidth / a * e, 
            (!s.data[i] || s.data[i] && result[i] < s.data[i]) && s.setData({
              result: s.data.result
            });
          }
      });
    },
    specHeight: function(t) {
      var a = t.detail.width, e = t.detail.height, i = t.target.dataset.type, s = this;
      wx.getSystemInfo({
        success: function(t) {
          s.data.result[i] = t.windowWidth / a * e, 
          (!s.data[i] || s.data[i] && result[i] < s.data[i]) && s.setData({
            result: s.data.result
          });
        }
      });
    },
    getCart: function() {
      let t = this;
      e.get("merch/cart/get_cart", {
        type: t.data.type,
        cart_type: t.data.type,
        merchid: t.data.merchid,
      }, function(r) {
        t.setData({
          shopTotal: r.total,
          shopTotalprice: r.totalprice,
        })
      });
    },
    coupon: function() {
      var th = this, coupon = th.data.coupon, shid = th.data.merchid;
      if(coupon){
        th.setData({ cover: false, shop: false, });
      } else{
        wx.showToast({ 
          title: "加载中...", 
          icon: "loading", 
          mask: true,
          duration: 100000,
        })
        e.get("merch/get_coupon_list", {
          shanghuid: shid,
        }, function(r) {
          if(r.error==0) 
            th.setData({
              cover: true,
              coupon: true,
              couponList: r.list,
            }), wx.hideToast();
        });
      }
    },
    // 领取优惠券
    receive: function(p) {
      let userinfoOpenid = t.getCache("userinfo_openid"), 
          th = this, couponid = p.currentTarget.dataset.couponid;
        if(!userinfoOpenid) {
          wx.navigateTo({ url: "/pages/auth/index" })
          return;
        }
        wx.showToast({ 
          title: "加载中...", 
          icon: "loading", 
          mask: true,
          duration: 100000,
        })
        e.get("merch/get_coupon", {
          id: couponid,
        }, function(r) {
          if(r.error==0){
            foxui.toast(th, "领取成功");
            th.setData({ cover: false, coupon: false, });
          }else{
            e.alert(r.message);
          }
          wx.hideToast(); 
        });
    },
    option: function(p) {
      let userinfoOpenid = t.getCache("userinfo_openid"),
          th = this, goodsid = p.currentTarget.dataset.goodsid;
      if(!userinfoOpenid) {
        wx.navigateTo({ url: "/pages/auth/index" })
        return;
      }
      var height = wx.getSystemInfoSync().windowHeight;
      wx.showToast({ 
        title: "加载中...", 
        icon: "loading", 
        mask: true,
        duration: 100000,
      })
      e.get("merch/cart/getgoods", {
        type: th.data.type,
        id: goodsid,
      }, function(r) {
        if(r.error==0){
          let specs = [], len = 0, content = r.goods.content;
          if(r.specs){
            specs = r.specs, len = specs.length;
            // 处理数组添加 isSelect 方便选中
            for (var i = 0; i < specs.length; i++) {
              for (var o = 0; o < specs[i].items.length; o++) {
                specs[i].items[o].isSelect = false
              }
            }
            r.specs = specs;
          }
          if(content) wxParse.wxParse("content", "html", content, th, 0);
          else wxParse.wxParse("content", "html", " ", th, 0);
          th.setData({
            spec: true,
            cart_num: 1,
            specHeight: height,
            specs: specs,
            options: r.options,
            specGoods: r,
            specbanner: r.goods.thumbs,
            goodsid: goodsid,
            speclength: len,
            specGoodsMarketprice: r.goods.marketprice,
          }) , th.init_attr();
        }else{
          e.alert("参数错误");
        }
        wx.hideToast(); 
      });
    },
    specBtn: function(p) {
      var that = this;
      var selectIndex = p.currentTarget.dataset.parentindex;
      var attrIndex = p.currentTarget.dataset.index;
      var spec = that.data.specs;
      var options = that.data.options;
      var count = spec[selectIndex].items.length;
      // console.log(count); return;
      for (var i = 0; i < count; i++) {
        spec[selectIndex].items[i].isSelect = false;
      }
      spec[selectIndex].items[attrIndex].isSelect = true;
      var thumb = spec[selectIndex].items[attrIndex].thumb;
      if(thumb) {
        that.setData({
          specbanner: [thumb],
        });
      }
      var name = spec[selectIndex].items[attrIndex].title;
      var attrid = spec[selectIndex].items[attrIndex].id;
      // 点击过，修改属性
      var selectName = "";
      // 点击过，修改属性
      selectIndexArray[selectIndex].value = name;
      selectAttrid[selectIndex] = attrid;
      console.log(attrid);
      var selectIndexArraySize = selectIndexArray.length;
      // 将数组的所有属性名拼接起来
      for (var i = 0; i < selectIndexArraySize; i++) {
        if(selectIndexArray[i].value){
          if(i==selectIndexArraySize-1)
            selectName += '' + selectIndexArray[i].value + '';
          else
            selectName += '' + selectIndexArray[i].value + ',';
        }
      }
      var selectNameSplit = selectName.split(",");
      for(var j=0; j<options.length; j++) {
        if(options[j].title == selectNameSplit.join('+')){
          if(options[j].thumb) {
            that.setData({
              specbanner: options[j].thumb,
            });
          }
          that.setData({
            optionid: options[j].id,
            specGoodsMarketprice: options[j].marketprice,
          });
        }
      }
      that.setData({
        specs: spec,
        selectName: selectName,
        selectAttrid: selectAttrid,
      });
    },
    init_attr: function () {
      // 初始化规格选择
      var name = "";
      var spec = this.data.specs;
      var size = spec.length;
      for (var i = 0; i < size; i++) {
        selectIndexArray.push({ key: i, value: spec[i].items[0].name });
        // 默认值初始化
        selectAttrid = [];
        // name += ' "' + selectIndexArray[i].value + '" ';
      }
      // 默认值初始化
      // var selectName = this.data.selectName;
      // selectName = name;
      // this.setData({
      //   selectName: selectName,
      //   selectAttrid: selectAttrid
      // });
    },
    specScrolltoupper: function(e) {
      let t =  e.detail.scrollTop;
      if (t > 200 && !this.data.specFloorstatus) {
        this.setData({
          specFloorstatus: true
        });
      } 
      if(t <= 200 && this.data.specFloorstatus){
        this.setData({
          specFloorstatus: false
        });
      }
    },
    specGoTop: function() {
      this.setData({
        specTopNum: 0
      });
    },
    // 加入购物袋加减
    specMinus: function () {
      var num = this.data.cart_num;
      if (num > 1) num--;
      // 只有大于一件的时候，才能normal状态，否则disable状态
      // var minusStatus = num <= 1 ? "disabled" : "normal";
      this.setData({
        cart_num: num,
      });
    },
    specPlus: function () {
      var num = this.data.cart_num;
      num++;
      // 只有大于一件的时候，才能normal状态，否则disable状态
      // var minusStatus = num < 1 ? "disabled" : "normal";
      this.setData({
        cart_num: num,
      });
    },
    addbag: function(p) {
      var th = this, merchid = th.data.merchid, total = th.data.cart_num,
      goodsid = th.data.goodsid, len = th.data.speclength, cart_type = th.data.type,
      optionid = th.data.optionid, selectAttrid = th.data.selectAttrid, 
      c = {};
      console.log(th.data.selectAttrid);
      e.post("merch/cart/checkgoods", {goodsid:goodsid,selectAttrid:selectAttrid} , function(res) {
        console.log(res);
        if(res.can_add==0) {
          foxui.toast(th, res.msg);
          return false;
        }
        c.total    = total, 
        c.cart_type= cart_type,
        c.id       = goodsid,
        c.merch    = merchid, 
        c.optionid = res.optionid;
        wx.showToast({ 
          title: "加载中...", 
          icon: "loading", 
          mask: true,
          duration: 100000,
        })
        e.post("merch/cart/add", c , function(r) {
          if(r.error==0){
            foxui.toast(th, "添加成功"),
            th.setData({
              spec: false,
              selectName: "",
              selectAttrid: "",
              optionid: "",
            }), th.getCart(), wx.hideToast();
            selectIndexArray = [],
            selectAttrid = [];
          }else{
            foxui.toast(th, r.message);
          }
        });
      });
      return;
    },
    specClose: function() {
      this.setData({
        spec: false,
        selectName: [],
        selectAttrid: [],
        optionid: "",
      }),
      selectIndexArray = [],
      selectAttrid = [];
    },
    shoping: function() {
      let that = this, shop = that.data.shop;
      let userinfoOpenid = t.getCache("userinfo_openid");
      if(!userinfoOpenid) {
        wx.navigateTo({ url: "/pages/auth/index" })
        return;
      }
      if(shop){
        that.setData({ cover: false, shop: false, });
      } else{
        wx.showToast({ 
          title: "加载中...", 
          icon: "loading", 
          mask: true,
          duration: 100000,
        })
        e.get("merch/cart/get_cart", {
          type: that.data.type,
          cart_type: that.data.type,
          merchid: that.data.merchid,
        }, function(r) {
          that.setData({
            shop: true, 
            cover: true, 
            shopBag: r,
            bagList: r.list,
          }), wx.hideToast();
          that.getCart();
        });
      }
    },
    selected: function() {
      console.log("selected");
    },
    // 购物袋内加减
    bagMinus: function (p) {
      var that = this, dataset = p.currentTarget.dataset,
        merchid = that.data.merchid, id = dataset.goodsid,
        optionid = dataset.optionid, index = dataset.index,
        num = that.data.bagList[index].total,
        key = 'bagList['+index+'].total';
      let del_index = parseInt(dataset.index);
      var obj = {};
      wx.showToast({ 
        title: "加载中...", 
        icon: "loading", 
        mask: true,
        duration: 100000,
      })
      if(num<=1){ // 如果购物车的数量小于零，则删除此商品
        //obj[key] = 1;
        that.data.bagList.splice(del_index, 1);//表示从第del_index个开始删，删1个
        e.post("merch/cart/update", {
          id: id, merchid: merchid, optionid: optionid, total: 0, cart_type: that.data.type,
        }, function(r) {
          that.setData({
            bagList: that.data.bagList
          }), wx.hideToast();
          that.getCart()
        })
      }else{
        num--;
        obj[key] = num;
        e.post("merch/cart/update", {
          id: id, merchid: merchid, optionid: optionid, total: num, cart_type: that.data.type,
        }, function(r) {
          wx.hideToast();
          that.getCart();
          that.setData(obj);
        })
      }
    },
    bagPlus: function (p) {
      var that = this, dataset = p.currentTarget.dataset,
        merchid = that.data.merchid, id = dataset.goodsid,
        optionid = dataset.optionid, index = dataset.index,
        num = parseInt(that.data.bagList[index].total)+1,
        key = 'bagList['+index+'].total';
      var obj = {};
      wx.showToast({ 
        title: "加载中...", 
        icon: "loading", 
        mask: true,
        duration: 100000,
      })
      e.post("merch/cart/update", {
        id: id, merchid: merchid, optionid: optionid, total: num, cart_type: that.data.type,
      }, function(r) {
        obj[key] = num;
        that.setData(obj);
        wx.hideToast();
        that.getCart();
      });
    },
    checkall: function() {
      console.log("checkall");
    },
    empty: function() {
      var that = this;
      wx.showToast({ 
        title: "加载中...", 
        icon: "loading", 
        mask: true,
        duration: 100000,
      })
      e.get("merch/cart/remove", {
        type: that.data.type,
        cart_type: that.data.type,
        merchid: that.data.merchid,
      }, function(r) {
          that.setData({
            shopTotal: 0,
            shopTotalprice: 0,
            bagList: [],
          }), wx.hideToast();
      });
    },
    hide: function() {
      this.setData({ cover: false, coupon: false, shop: false, });
    },
    // 结算
    submit: function() {
      let userinfoOpenid = t.getCache("userinfo_openid");
      if(!userinfoOpenid) {
        wx.navigateTo({ url: "/pages/auth/index" })
        return;
      }
      var that = this;
      wx.showToast({ 
        title: "加载中...", 
        icon: "loading", 
        mask: true,
        duration: 100000,
      })
      
      e.get("merch/cart/submit", {
        type: that.data.type,
        cart_type: that.data.type,
        merchid: that.data.merchid,
      }, function(r) {
        if(r.error==0)
          that.setData({
            cover: false, shop: false,
          }),
          wx.navigateTo({
            url: "/store/order/create/index?type="+that.data.type+"&merchid="+that.data.merchid+"&cart_type="+that.data.type,
          })
        else 
          e.alert("参数错误");
        wx.hideToast();
      });
    },
    // onReachBottom: function() {
    //   this.data.loaded || this.data.list.length == this.data.total || this.getList();
    // },
    lower: function() {
      this.data.loaded || this.data.list.length == this.data.total || this.getList();
    },
    onPullDownRefresh: function() {
      wx.stopPullDownRefresh();
    },
    receivenew: function(p) {
      var c_url = p.currentTarget.dataset.url;
      wx.navigateTo({ url: c_url })
      return;
    },
});